package hw.ats.news.activity.news;

import hw.ats.apps.AbstractStartupAct;
import hw.ats.news.R;
import hw.ats.news.activity.DBAwareActivity;
import hw.ats.news.ds.NewsParser;
import hw.ats.news.model.Cate;
import hw.ats.news.model.News;
import hw.ats.news.ui.BottomTabHostProvider;
import hw.ats.news.ui.CateNavCallback;
import hw.ats.news.ui.CateNavHolder;
import hw.ats.news.ui.CommonUI;
import hw.ats.news.ui.NewsResourceHolder;
import hw.ats.news.util.App;
import hw.ats.news.util.DataLoader;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.humanwares.ui.asyncimage.ImageDisplayer;
import com.humanwares.ui.asyncimage.ImageReceivedCallback;
import com.humanwares.ui.asyncimage.ImageReceiver;
import com.humanwares.ui.tabbar.TabHost;
import com.tattermedia.allthataudio.audio.AudioPlayerDialogTool;
import com.tattermedia.allthataudio.audio.AudioPlayerManager;
import com.tattermedia.allthataudio.audio.CommonAudioPlayerStatusListener;
import com.tattermedia.allthataudio.audio.IAudioPlayerStatusListener;
import com.tattermedia.allthataudio.misc.DebugFlag;
import com.tattermedia.allthataudio.views.AudioPlayerProgressView;
import com.tattermedia.allthataudio.views.SharedBitmap;

public class RecentAct extends DBAwareActivity implements ImageReceivedCallback, CateNavCallback {
	private static final String TAG = "RecentAct";
	
	private List<Cate> cates = null;
	private List<News> items = new ArrayList<News>();
	private ListView listView = null;
	private TabHost navbar = null;
	
	// audio status listener
	private IAudioPlayerStatusListener		mAudioStatusListener;
	
	// 페이징
	private int start = 0;
	private int rows = App.ROW_PER_PAGE;
	private int items_count  = App.ITEMS_PER_PAGE;
	private boolean hasNext = true;
	
	// 썸네일 출력 여부
	private boolean thumbDisplay = false;
	
	// 현재 선택된 카테고리
	private Cate cate = null;
	
	private int page = 1;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        thumbDisplay = pref.getBoolean("pref_list_thumb", true);
        
        initData();
        
        // init shared bitmap
        SharedBitmap.getInstance().initialize(this.getResources());
     
        
        setContentView(R.layout.act_recent);
        
        // 탭바 초기화
        navbar = CommonUI.renderTabBar(this, BottomTabHostProvider.TAB1);
        
		// 네비게이션바 제목
        CommonUI.renderAppTitle(this);
        
        // 좌측 네비게이션 버튼 = 검색화면이동
        CommonUI.addLeftNavigationButtonSearchEvent(this);
        
        // 우측 네비게이션 버튼 = All That 화면이동
        CommonUI.addRightNavigationButtonAllThatEvent(this);
        
        // 서브네비게이션바 생성
        CommonUI.makeWithCategorizedSubNavigation(this, cates, cate == null ? 0 : cate.uid);
        
        // 다른 화면에서 카테고리로 접근이 되었을 때 카테고리 위치를 기존 화면과 맞추어줌
        Intent intent = getIntent();
        final int scrollX = intent.getIntExtra(App.INTENT_EXTRA_SCROLL_X, -1);
        if (scrollX >= 0) {
        	final HorizontalScrollView sv = (HorizontalScrollView)findViewById(R.id.navcat_scroll);
        	sv.post(new Runnable() {
				@Override
				public void run() {
					sv.scrollTo(scrollX, 0);
				}
			});
        }
        
        // 분류로 조회시
        if (cate != null) {
			TextView titleView = (TextView) findViewById(R.id.topbar_title);
			if (titleView != null && cate != null)
				titleView.setText("최신글 > " + cate.title);
        }
        
        // add audio status listener
        mAudioStatusListener = new CommonAudioPlayerStatusListener(
        		(ImageButton)findViewById(R.id.audio_player_button_play), 
        		(ImageButton)findViewById(R.id.audio_player_button_repeat),
        		(ImageButton)findViewById(R.id.audio_player_button_prev),
        		(ImageButton)findViewById(R.id.audio_player_button_next),
        		(TextView)findViewById(R.id.audio_player_text_subject),
        		(TextView)findViewById(R.id.audio_player_text_time),
        		(AudioPlayerProgressView)findViewById(R.id.audio_player_progress_view));
        
        AudioPlayerManager.getManager().addAudioPlayerStatusListener(mAudioStatusListener);
        mAudioStatusListener.onAudioStatusChanged(IAudioPlayerStatusListener.TYPE_COMMON);

       
        
        showArt();
        
        
        
    }
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		
		AudioPlayerManager.getManager().removeAudioPlayerStatusListener(mAudioStatusListener);
		
		if (DebugFlag.isLogEnabled()) Log.d(TAG, "onDestroy()");
		closeDatabase();
	}
    
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event)  {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//	    	Intent intent = new Intent(RecentAct.this, RecmdAct.class);
//	    	startActivity(intent);
//	    	finish();
//	    	overridePendingTransition(0, 0);
//            return true;
//        }
//
//        return super.onKeyDown(keyCode, event);
//    }
    
    /**
     * 이미지 로더
     */
	public void onImageReceived(ImageDisplayer displayer) {
//		this.runOnUiThread(displayer);
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        int visibility = navbar.getVisibility();
        navbar.setVisibility(visibility == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
        return false;
    }
    
	@Override
	public void onSelectCateNav(int position, CateNavHolder holder) {
		if (DebugFlag.isLogEnabled()) 
			Log.d(TAG, "position="+position);
		
		Cate cate = holder.select(position);
		
		if (DebugFlag.isLogEnabled()) 
			Log.d(TAG, "cate="+cate.title +" uid=" +String.valueOf(cate.uid));
		
		this.cate = cate;
		RecentAct.this.cate = cate;
		this.hasNext = false;
		this.page = 1;
		
		TextView titleView = (TextView)findViewById(R.id.topbar_title);
		titleView.setText("최신글 > " + cate.title);
		
       	new AsyncTask<String, Integer, Boolean>() {
    		private ProgressDialog progressDialog;
    		
    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    	    	progressDialog = ProgressDialog.show(
    	    			RecentAct.this, App.APP_TITLE, "글을 수신하고 있습니다.", true, false);
    		}
    		
			@Override
			protected Boolean doInBackground(String... params) {
				

				NewsParser parser = new NewsParser();
				Log.d("Recent Act ", "fetching data from web.. cate id is "+ String.valueOf(RecentAct.this.cate.uid));
				List<News> newItems = (RecentAct.this.cate == null || RecentAct.this.cate.uid == 0)?
						parser.parse(App.NEWS_XML_URL + String.valueOf(RecentAct.this.page) ):
							parser.parse(App.NEWS_CATE_XML_URL + String.valueOf(RecentAct.this.cate.uid) + "&page="+String.valueOf(RecentAct.this.page));
	
				//items  = parser.parse(App.NEWS_CATE_XML_URL + String.valueOf(RecentAct.this.cate.uid) +"&page="+String.valueOf(RecentAct.this.page));


						for (int i = 0, len = newItems.size(); i < len; i++) {
							News news = items.get(i);
							
							
							News dbNews = News.load(getReadableDatabase(), news.uid);
							
							if (dbNews == null) {
//								DataLoader.loadNewsBody(getDBHelper(), news, false);
								news.insert(getWritableDatabase());
								
							} else {
								news = dbNews;
							}
							
							items.add(news);
						}
						Log.d("ITEMS SIZE",String.valueOf(items.size()));
						if (items.size() == items_count ) {
							RecentAct.this.hasNext = true;
							//this.page += 1;
						} else {
							RecentAct.this.hasNext = false;
						}
						
						

				// block loading categories
				
//				if (RecentAct.this.cate != null && RecentAct.this.cate.uid > 0)
//					DataLoader.loadCateNews(getDBHelper(), RecentAct.this.cate.uid);
//				
//				items = News.list(getReadableDatabase(), RecentAct.this.cate.uid, 0, rows + 1);
//				if (items != null && items.size() == rows + 1) {
//					items.remove(rows);
//					hasNext = true;
//				}
				
				return true;
			}
			
			@Override
			protected void onProgressUpdate(Integer... progress) {

			}

			@Override
			protected void onPostExecute(Boolean result) {
				listView.setAdapter(new RecentAdapter(RecentAct.this));
				progressDialog.dismiss();
				if (result == false) {
					Toast.makeText(RecentAct.this, "최신 글을 수신할 수 없습니다.\n네트워크 접속 상태를 확인하여 주십시오.", Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected void onCancelled() {
				super.onCancelled();
				progressDialog.dismiss();
			}
		}.execute();
	}
	
	/**
	 * 최신글 목록
	 */
	private void showArt() {
        listView = (ListView)findViewById(R.id.news_list);
        listView.setAdapter(new RecentAdapter(this));
        listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				News news = items.get(position);
				Intent intent = new Intent(RecentAct.this, ViewAct.class);
				intent.putExtra(App.INTENT_EXTRA_NEWS_UID, news.uid);
				intent.putExtra(App.INTENT_EXTRA_CATE_UID, cate != null ? cate.uid : 0);
				intent.putExtra(App.INTENT_EXTRA_ACT_NAME, RecentAct.class.getName());
			    startActivity(intent);
			}
        });
	}
	
	/**
	 * 데이터 로딩
	 */

	private void loadData(){
		NewsParser parser = new NewsParser();
		Log.d("Recent Act ", "fetching data from web");
		List<News> newItems = (this.cate == null || this.cate.uid == 0 )?
				parser.parse(App.NEWS_XML_URL + String.valueOf(this.page) ):
					parser.parse(App.NEWS_CATE_XML_URL + String.valueOf(this.cate.uid) + "&page="+String.valueOf(this.page));

				for (int i = 0, len = newItems.size(); i < len; i++) {
					News news = newItems.get(i);
					
					News dbNews = News.load(getReadableDatabase(), news.uid);
					
					if (dbNews == null) {
//						DataLoader.loadNewsBody(getDBHelper(), news, false);
						news.insert(getWritableDatabase());
						
					} else {
						news = dbNews;
					}
					
					items.add(news);
				}
				Log.d("ITEMS SIZE",String.valueOf(newItems.size()));
				if (newItems.size() == items_count ) {
					this.hasNext = true;
				} else {
					this.hasNext = false;
				}
				
		if (newItems.size() == 0) {
			loadData_legacy();
		}
	}

	
	/**
	 * 데이터 로딩
	 */
	private void loadData_legacy() {
		hasNext = false;
		List<News> newItems = (cate == null) ? 
				News.list(getReadableDatabase(), start, rows + 1) : 
					News.list(getReadableDatabase(), cate.uid, start, rows + 1);
		if (newItems != null && newItems.size() > 0) {
			if (newItems.size() == rows + 1) {
				newItems.remove(rows);
				hasNext = true;
			}
			items.addAll(newItems);
		}
	}
	
	/**
	 * 데이터 초기 로딩
	 */
	private void initData() {
		// 카테고리 (초기로딩시에만 로딩하고 페이징시에는 사용하지 않는다)
		cates = Cate.list(getReadableDatabase());
		
		cate = null;
		int catId = getIntent().getIntExtra(App.INTENT_EXTRA_CATE_UID, 0);
		if (catId > 0) {
			cate = Cate.load(getReadableDatabase(), catId);
			if (DebugFlag.isLogEnabled())
				Log.d(TAG, "cate="+cate);
		}
		
		loadData();
//		loadData_legacy();
	}
    
	/**
	 * 다음 페이지 데이터 조회
	 */
    private void loadNextData() {
    	start += App.ROW_PER_PAGE;
    	this.page += 1;
    	new AsyncTask<String, Integer, Boolean>() {
    		private ProgressDialog progressDialog;
    		
    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    	    	progressDialog = ProgressDialog.show(
    	        		RecentAct.this, "알림", "글을 조회하고 있습니다.", true, false);
    		}
    		
			@Override
			protected Boolean doInBackground(String... params) {
//				loadData_legacy();
				loadData();
				return true;
			}
			
			@Override
			protected void onProgressUpdate(Integer... progress) {
			}

			@Override
			protected void onPostExecute(Boolean result) {
				((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
				progressDialog.dismiss();
			}

			@Override
			protected void onCancelled() {
				super.onCancelled();
				progressDialog.dismiss();
			}
		}.execute();
    }
	
	private class RecentAdapter extends BaseAdapter {
		private final static String TAG = "RecentAdapter";
	   	private final Activity context;

        public RecentAdapter(Activity context) {
        	this.context = context;
        }

        public int getCount() {
        	if (items == null)
        		return 0;
        	
        	return items.size() + (hasNext ? 1 : 0);
        }

        public Object getItem(int position) {
            return items.get(position);
        }

        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            NewsResourceHolder holder = null;
            
            // 페이징
            if (items.size() == position) {
            	LayoutInflater vi = context.getLayoutInflater();
            	view = vi.inflate(R.layout.row_more_article, null);
            	ImageButton btn = (ImageButton)view.findViewById(R.id.row_more_btn);
            	btn.setOnClickListener(new OnClickListener() {
        			@Override
        			public void onClick(View v) {
        				loadNextData();
        			}
        		});
            	return view;
            }
            
            if (view == null || view.getTag() == null) {
            	LayoutInflater vi = context.getLayoutInflater();
//            	if (thumbDisplay)
//            		view = vi.inflate(R.layout.row_news_type2, null);
//            	else
            		view = vi.inflate(R.layout.row_news_type1, null);
                holder = new NewsResourceHolder(view);
                view.setTag(holder);
            } else {
            	holder = (NewsResourceHolder)view.getTag();
            }
            
            final News entry = items.get(position);
    		if (entry == null) {
    			return view;
    		}
    		
//            if (holder.imageView != null) {
//            	holder.imageView.setTag(position);
//            	holder.imageView.setImageResource(App.RES_LOADING_110x75);
//                new ImageReceiver(entry.thumb_default, (ImageReceivedCallback)context, 
//                		holder.imageView, getThumbPath(), position);
//                
//                if (DebugFlag.isLogEnabled()) 
//                	Log.d(TAG,
//                		"pos="+position+
//                		" img="+holder.imageView+
//                		" cv="+convertView+
//                		" par="+parent);
//            }
            
            if (entry.body_text == null || entry.body_text.length() == 0) {
	            if (holder.titleView != null)
	            	holder.titleView.setText("");
	            if (holder.titleOnlyView != null)
	            	holder.titleOnlyView.setText(entry.title);
	            if (holder.detailView != null)
	            	holder.detailView.setText("");
            } else {
	            if (holder.titleView != null)
	            	holder.titleView.setText(entry.title);
	            if (holder.titleOnlyView != null)
	            	holder.titleOnlyView.setText("");
	            if (holder.detailView != null) {
	            	int len = entry.body_text.length();
	            	if (len > 256) len = 256;
	            	holder.detailView.setText(entry.body_text.substring(0, len));
	            }
            }
            
            
            // set audio play button
            if (holder.button != null) {
            	holder.button.setFocusable(false);
            	holder.button.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						AudioPlayerDialogTool.showPlayOrAddDialog(RecentAct.this, entry);
					}
				});
            	
            	if (entry.mp3_url.trim().length() == 0) {
            		holder.button.setEnabled(false);
            	} else {
            		holder.button.setEnabled(true);
            	}
            }
            
    		
    		return view;
        }
	}
	
	@Override
	public void onBackPressed() {
		if (AudioPlayerManager.getManager().isPlaying()) {
			Intent setIntent = new Intent(Intent.ACTION_MAIN);
			setIntent.addCategory(Intent.CATEGORY_HOME);
			setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(setIntent);
		} else {
			
			super.onBackPressed();
			System.exit(0);
		}
	}
}
